<template>
  <view class="cart">
    <!-- 添加地址开始 -->
    <view class="address">
      <view class="addres_btn" v-if="!address">
        <!-- 添加地址按钮 -->
        <button type="primary" plain="true" @tap="handleAddress">请添加收货地址</button>
      </view>
      <view class="addres_info" v-else="">
        <!-- 展示地址 -->
        <view class="info-title">收货地址：</view>
        <view class="info-addres" @tap="handleAddress">{{ address }}</view>
      </view>
    </view>
    <!-- 添加地址结束 -->
    <!-- 购物车开始 -->
    <view class="cart_list_container">
      <!-- 标题 -->
      <view class="cart_title">购物车</view>
      <view class="cart_none" v-if="cart.length <= 0">您的购物车空空如也</view>
      <!-- 商品块 -->
      <view class="cart_list_item" v-for="(item, index) in cart" :key="item.goods_id" v-else="">
        <view class="chb_warper">
          <!-- 多选框组-->
          <checkbox-group name="cartList" :data-id="item.goods_id" @change="cartListChecked">
            <!-- 选择框 -->
            <checkbox :value="item.goods_id" :checked="item.checked" />
          </checkbox-group>
        </view>
        <navigator open-type="navigate" :url="'../goods_detail/goods_detail?goods_id=' + item.goods_id">
          <!-- 图片 -->
          <image :src="item.goods_small_logo" mode="widthFix"></image>
        </navigator>
        <view class="good_info_row">
          <view class="good_name">
            <!-- 商品名字 -->
            {{ item.goods_name }}
          </view>
          <view class="good_price_num">
            <view class="good_price">¥{{ item.goods_price }}</view>
            <view class="good_edit_row">
              <button type="primary" size="mini" @tap="addGoodNum(item.goods_id, -1)">-</button>
              <input type="number" :value="item.num" maxlength="5" disabled="true" />
              <button type="primary" size="mini" @tap="addGoodNum(item.goods_id, +1)">+</button>
            </view>
          </view>
        </view>
      </view>
    </view>
    <!-- 购物车结束 -->
    <!-- 底部工具栏开始 -->
    <view class="btm_tools">
      <!-- 全选 -->
      <view class="all_checked">
        <!-- 全选框 -->
        <checkbox-group name="" @change="allListChecked">
          <label>
            <checkbox :checked="allChecked" />
            <text>全选</text>
          </label>
        </checkbox-group>
      </view>
      <!-- 总价 -->
      <view class="tatal_price_row">
        <view class="total_price_warper">
          <text>合计：</text>
          <text class="total_price">¥{{ totalPrice }}</text>
          <view class="total_price_extra">包含运费</view>
        </view>
      </view>
      <!-- 结算 -->
      <view class="order_pay" @tap="goPayPage">结算({{ totalNum }})</view>
    </view>
    <!-- 底部工具栏结束 -->
  </view>
</template>

<script>
import regeneratorRuntime from '../../lib/runtime/runtime.js';
import { uniGetSetting, uniOpenSetting, uniChooseLocation, uniShowToast } from '../../utils/utils.js';
export default {
  onShow() {
    this.showCart();
  },
  data() {
    return {
      address: '',
      cart: [],
      allChecked: false,
      totalNum: 0,
      totalPrice: 0
    };
  },
  methods: {
    /* 刷新购物车页面 */
    showCart() {
      var _me = this;
      // 取缓存购物车
      _me.address = uni.getStorageSync('address');
      _me.cart = uni.getStorageSync('cart') || [];
      // 设置变量，全选，总数，总价
      var allChecked = _me.cart.length == 0 ? false : true;
      var totalNum = 0;
      var totalPrice = 0;
      // 遍历计算：全选，总数，总价
      _me.cart.forEach(function(item, index) {
        if (item.checked == true) {
          totalNum = totalNum + 1;
          totalPrice = totalPrice + item.goods_price * item.num;
        } else {
          allChecked = false;
        }
      });
      _me.allChecked = allChecked;
      _me.totalNum = totalNum;
      _me.totalPrice = totalPrice;
    },
    /* 获取收获地址 */
    async handleAddress() {
      var _me = this;

      // #ifdef MP
      try {
        // 取设置
        var res = await uniGetSetting();
        // console.log('获取设置的回调', res);
        // 获取 userLocation 权限状态
        var scopeUserLocation = res.authSetting['scope.userLocation'];
        // console.log('权限状态', scopeUserLocation);
        // 判断是否有权限
        if (scopeUserLocation == false) {
          // 没有 userLocation 权限
          var res2 = await uniOpenSetting();
          // console.log('打开设置的回调', res2);
        } else {
          // 有 userLocation 权限 或 没有授权过
        }
      } catch (error) {
        console.log('[getSetting]', error);
      }
      // #endif
      try {
        var res3 = await uniChooseLocation();
        // console.log('选择地址的回调', res3);
        console.log(res3.address);
        _me.address = res3.address;
        uni.setStorageSync('address', _me.address);
        var res4 = await uniShowToast({
          title: '选择地址成功',
          mask: true,
          duration: 1000
        });
      } catch (error) {
        //TODO handle the exception
        switch (error.errMsg) {
          case 'chooseLocation:fail auth deny':
            var res4 = await uniShowToast({
              title: '没有选择地址权限',
              mask: true,
              icon: 'none',
              duration: 1000
            });
            console.log('[chooseLocation]', '没有选择地址权限');
            break;
          case 'chooseLocation:fail':
          case 'chooseLocation:fail cancel':
            var res4 = await uniShowToast({
              title: '取消选择地址',
              mask: true,
              icon: 'none',
              duration: 1000
            });
            console.log('[chooseLocation]', '取消选择地址');
            break;
          default:
            console.log('[chooseLocation]异常', error);
            break;
        }
      }
    },
    /* 增加或减少数量 */
    addGoodNum(goods_id, number) {
      var _me = this;
      var index = _me.cart.findIndex(function(item) {
        return item.goods_id == goods_id;
      });
      _me.cart[index].num = _me.cart[index].num + number;
      if (_me.cart[index].num <= 1) {
        uni.showModal({
          title: '提示',
          content: '确定要移除该商品吗？',
          confirmText: '确定',
          confirmColor: '#3CC51F',
          showCancel: true,
          cancelText: '取消',
          cancelColor: '#000000',
          success(e) {
            // console.log(e);
            if (e.confirm) {
              _me.cart.splice(index, 1);
              console.log(_me.cart);
            } else {
              _me.cart[index].num = 1;
            }
          },
          complete() {
            uni.setStorageSync('cart', _me.cart);
            _me.showCart();
          }
        });
      } else {
        uni.setStorageSync('cart', _me.cart);
        _me.showCart();
      }
    },
    /* 选中被改变 */
    cartListChecked(e) {
      var _me = this;
      var goods_id = e.currentTarget.dataset.id;
      var index = _me.cart.findIndex(function(item) {
        return item.goods_id == goods_id;
      });

      // 是否选中
      if (e.detail.value[0] != undefined) {
        // 选中
        _me.cart[index].checked = true;
      } else {
        // 未选中
        _me.cart[index].checked = false;
      }
      uni.setStorageSync('cart', _me.cart);
      _me.showCart();
    },
    /* 全选被改变 */
    allListChecked(e) {
      var _me = this;
      // 是否选中
      if (e.detail.value[0] != undefined) {
        // 选中
        _me.cart.forEach(function(item) {
          item.checked = true;
        });
      } else {
        // 未选中
        _me.cart.forEach(function(item) {
          item.checked = false;
        });
      }
      uni.setStorageSync('cart', _me.cart);
      _me.showCart();
    },
    /* 去支付 */
    goPayPage() {
      var _me = this;
      // 是否选择地址
      if (_me.address != '') {
        // 已选择地址
        // 是否选择商品
        if (_me.totalNum > 0) {
          // 已选择商品
          uni.navigateTo({
            url: '../pay/pay'
          });
        } else {
          // 未选择商品
          uni.showToast({
            title: '未选择商品',
            icon: 'none'
          });
        }
      } else {
        // 未选择地址
        uni.showToast({
          title: '未选择地址',
          icon: 'none'
        });
      }
    }
  }
};
</script>

<style lang="scss">
.cart {
  padding-bottom: 90rpx;
  /* 添加地址开始 */
  .address {
    height: 136rpx;
    .addres_btn {
      padding: 20rpx 0;
      button {
        font-size: 36rpx;
        width: 50%;
        margin: 0 auto;
      }
    }
    .addres_info {
      padding: 10rpx 20rpx;
      .info-title {
        height: 36rpx;
        font-size: 36rpx;
      }
      .info-addres {
        height: 70rpx;
        margin-top: 10rpx;
        font-size: 36rpx;
        line-height: 36rpx;
        text-indent: 1em;
      }
    }
  }
  /* 添加地址结束 */
  /* 购物车开始 */
  .cart_list_container {
    .cart_title {
      color: $themeColor;
      padding: 20rpx;
      border: {
        top: 2rpx solid #cccccc;
        bottom: 2rpx solid #cccccc;
      }
    }
    .cart_none {
      height: 500rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 60rpx;
    }
    .cart_list_item {
      display: flex;
      padding: 20rpx 0rpx;
      border: {
        top: 2rpx solid #cccccc;
        bottom: 2rpx solid #cccccc;
      }
      .chb_warper {
        flex: 1;
        display: flex;
        justify-content: center;
        align-items: center;
        // background-color: #ff0000;
        checkbox-group {
          checkbox {
          }
        }
      }
      navigator {
        flex: 2;
        display: flex;
        justify-content: center;
        align-items: center;
        // background-color: #00ff00;
        image {
          width: 80%;
        }
      }
      .good_info_row {
        flex: 5;
        display: flex;
        flex-direction: column;
        justify-content: space-around;
        // background-color: #0000ff;
        .good_name {
          /* 超出隐藏 */
          display: -webkit-box;
          overflow: hidden;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 2;
        }
        .good_price_num {
          display: flex;
          justify-content: space-between;
          .good_price {
            color: $themeColor;
            font-size: 30rpx;
            font-weight: bolder;
          }
          .good_edit_row {
            display: flex;
            button {
              width: 50rpx;
              height: 50rpx;
              padding: 0rpx;
              border-radius: 0rpx;
              border-width: 2rpx;
              display: flex;
              justify-content: center;
              align-items: center;
              font-size: 36rpx;
              font-weight: bolder;
            }
            input {
              width: 100rpx;
              // #ifdef MP-WEIXIN
              height: 46rpx;
              // #endif
              // #ifndef MP-WEIXIN
              height: 50rpx;
              // #endif
              font-size: 32rpx;
              font-weight: bolder;
              text-align: center;
              border: 2rpx solid #cccccc;
            }
          }
        }
      }
    }
  }
  /* 购物车结束 */
  /* 底部工具栏开始 */
  .btm_tools {
    display: flex;
    z-index: 100;
    position: fixed;
    left: 0;
    bottom: var(--window-bottom);
    width: 100%;
    height: 90rpx;
    background-color: #ffffff;
    border-top: 2rpx solid #cccccc;
    .all_checked {
      flex: 2;
      display: flex;
      justify-content: center;
      align-items: center;
      checkbox-group {
        label {
          checkbox {
          }
          text {
          }
        }
      }
    }
    .tatal_price_row {
      flex: 5;
      display: flex;
      flex-direction: column;
      .total_price_warper {
        text-align: right;
        .total_price {
          color: $themeColor;
          font-size: 30rpx;
          font-weight: bolder;
        }
      }
      .total_price_extra {
        font-size: 30rpx;
      }
    }
    .order_pay {
      flex: 3;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 34rpx;
      font-weight: bolder;
      color: #ffffff;
      background-color: $themeColor;
    }
  }
  /* 底部工具栏结束 */
}
</style>
